package maple.core;

import java.util.HashMap;
import java.util.logging.Level;

import jade.lang.acl.ACLMessage;
import jade.wrapper.StaleProxyException;

import maple.lang.Command;
import maple.lang.Language;
import maple.util.Task;

public class Messenger extends MapleAgent
{
	private final int TIMEOUT = 15000;

	private long _begin_time;

	private HashMap< String, Language.Instruction > _commands; 

	public Messenger()
	{
		super();

		// from MapleAgent
		_min_arguments = 1;

		_begin_time = 0;
		_commands = new HashMap< String, Language.Instruction >();
	}

	protected void setup()
	{
		super.setup();
		
		String[] tokens = _arguments[ 0 ].split( "#" );
		for( String token : tokens )
		{
			int index = token.indexOf( Language.DELIMITER );
			if( index > 0 )
			{
				String receiver = token.substring( 0, index );
				Command command = new Command( token.substring( index + 1 ) );
				if( command.isAvailable() )
				{
					if( sendMessage( ACLMessage.REQUEST, receiver, command.toString(), null, null ) )
					{
						_commands.put( command.toString(), command.getInstruction() );
					}
				}
			}
		}

		if( _commands.isEmpty() )
		{
			doDelete();
		}
		_begin_time = System.currentTimeMillis();
	}

	protected String getLogFilename()
	{
		return "/dev/shm/" + getClass().getSimpleName() + ".log";
	}

	protected void takeDown()
	{
		try
		{
			getContainerController().kill();
		}
		catch( StaleProxyException e )
		{
			_logger.log( Level.WARNING, "", e );
		}
	}

	protected void actionInform( final ACLMessage message )
	{
		boolean finished = false;

		String content = message.getContent();
		String command = message.getUserDefinedParameter( Task.Property.COMMAND.toString() );
		
		if( _commands.containsKey( command ) )
		{
			try
			{
				if( Command.Message.valueOf( content ) == Command.Message.OK )
				{
					switch( _commands.get( command ))
					{
						case INSERT:
						case UPDATE:
						case DELETE:
							finished = true;
							break;
					}
				}
				else
				{
					finished = true;
				}
			}
			catch( IllegalArgumentException e )
			{
				_logger.log( Level.WARNING, "", e );
				finished = true;
			}
		}

		if( finished )
		{
			System.out.println( message.getSender().getName() + Language.DELIMITER + command + Language.DELIMITER + content );
			
			_commands.remove( command );
		
			if( _commands.isEmpty() )
			{
				doDelete();
			}
		}
	}

	protected void check()
	{
		if( ( System.currentTimeMillis() - _begin_time ) > TIMEOUT )
		{
			doDelete();
		}
	}
}
